package pt.uc.dei.mse.eai.ui;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.swing.JOptionPane;
import javax.xml.bind.JAXBException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;

import pt.uc.dei.mse.eai.model.dataModel.Cinema;
import pt.uc.dei.mse.eai.screenScrapping.CineSiteScrapper;
import pt.uc.dei.mse.eai.xmlBuilder.XMLBuilder;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUI.java
 *
 * Created on Sep 16, 2011, 4:26:24 PM
 */
/**
 * 
 * @author pjfaria
 */
public class GUI extends javax.swing.JFrame {

	private HashMap<String, String> hashCines;
	private CineSiteScrapper scrapper;

	/** Creates new form GUI */
	public GUI() {
		initComponents();
		fileError.setVisible(false);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		buttonGroup1 = new javax.swing.ButtonGroup();
		buttonGroup2 = new javax.swing.ButtonGroup();
		jDialog1 = new javax.swing.JDialog();
		jLabel4 = new javax.swing.JLabel();
		jLabel1 = new javax.swing.JLabel();
		jTextField1 = new javax.swing.JTextField();
		jScrollPane1 = new javax.swing.JScrollPane();
		jList1 = new javax.swing.JList();
		jLabel2 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jTextField2 = new javax.swing.JTextField();
		jPanel1 = new javax.swing.JPanel();
		jRadioButton1 = new javax.swing.JRadioButton();
		jRadioButton2 = new javax.swing.JRadioButton();
		jPanel2 = new javax.swing.JPanel();
		jRadioButton3 = new javax.swing.JRadioButton();
		jRadioButton4 = new javax.swing.JRadioButton();
		jButton1 = new javax.swing.JButton();
		jButton2 = new javax.swing.JButton();
		fileError = new javax.swing.JLabel();

		jDialog1.setName("jDialog1"); // NOI18N

		jLabel4.setText("Invalid filepath");
		jLabel4.setName("jLabel4"); // NOI18N

		org.jdesktop.layout.GroupLayout jDialog1Layout = new org.jdesktop.layout.GroupLayout(
				jDialog1.getContentPane());
		jDialog1.getContentPane().setLayout(jDialog1Layout);
		jDialog1Layout.setHorizontalGroup(jDialog1Layout.createParallelGroup(
				org.jdesktop.layout.GroupLayout.LEADING).add(
				jDialog1Layout.createSequentialGroup().add(31, 31, 31)
						.add(jLabel4).addContainerGap(38, Short.MAX_VALUE)));
		jDialog1Layout.setVerticalGroup(jDialog1Layout.createParallelGroup(
				org.jdesktop.layout.GroupLayout.LEADING).add(
				jDialog1Layout
						.createSequentialGroup()
						.addContainerGap()
						.add(jLabel4)
						.addContainerGap(
								org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
								Short.MAX_VALUE)));

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jLabel1.setText("URL to scrap:");
		jLabel1.setName("jLabel1"); // NOI18N

		jTextField1.setName("jTextField1"); // NOI18N
		jTextField1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField1ActionPerformed(evt);
			}
		});

		jScrollPane1.setName("jScrollPane1"); // NOI18N

		jList1.setName("jList1"); // NOI18N
		jScrollPane1.setViewportView(jList1);

		jLabel2.setText("Cinemas:");
		jLabel2.setName("jLabel2"); // NOI18N

		jLabel3.setText("Output filepath:");
		jLabel3.setName("jLabel3"); // NOI18N

		jTextField2.setText("http://cinecartaz.publico.pt/");
		//jTextField2.setEnabled(false);
		jTextField2.setName("jTextField2"); // NOI18N
		jTextField2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField2ActionPerformed(evt);
			}
		});

		jPanel1.setBorder(javax.swing.BorderFactory
				.createTitledBorder("Operation Mode"));
		jPanel1.setName("jPanel1"); // NOI18N

		buttonGroup1.add(jRadioButton1);
		jRadioButton1.setText("Online");
		jRadioButton1.setName("jRadioButton1"); // NOI18N

		buttonGroup1.add(jRadioButton2);
		jRadioButton2.setText("Offline");
		jRadioButton2.setName("jRadioButton2"); // NOI18N

		org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(
				org.jdesktop.layout.GroupLayout.LEADING).add(
				jPanel1Layout
						.createSequentialGroup()
						.add(jRadioButton1)
						.addPreferredGap(
								org.jdesktop.layout.LayoutStyle.RELATED)
						.add(jRadioButton2)));
		jPanel1Layout
				.setVerticalGroup(jPanel1Layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(jPanel1Layout
								.createSequentialGroup()
								.add(jPanel1Layout
										.createParallelGroup(
												org.jdesktop.layout.GroupLayout.BASELINE)
										.add(jRadioButton1).add(jRadioButton2))
								.addContainerGap(
										org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		jPanel2.setBorder(javax.swing.BorderFactory
				.createTitledBorder("Output Mode"));
		jPanel2.setName("jPanel2"); // NOI18N

		buttonGroup2.add(jRadioButton3);
		jRadioButton3.setSelected(true);
		jRadioButton3.setText("XML");
		jRadioButton3.setName("jRadioButton3"); // NOI18N

		buttonGroup2.add(jRadioButton4);
		jRadioButton4.setText("HTML");
		jRadioButton4.setName("jRadioButton4"); // NOI18N

		org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(
				jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(
				org.jdesktop.layout.GroupLayout.LEADING).add(
				jPanel2Layout
						.createSequentialGroup()
						.add(jRadioButton3)
						.addPreferredGap(
								org.jdesktop.layout.LayoutStyle.RELATED)
						.add(jRadioButton4)
						.addContainerGap(58, Short.MAX_VALUE)));
		jPanel2Layout
				.setVerticalGroup(jPanel2Layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(jPanel2Layout
								.createSequentialGroup()
								.add(jPanel2Layout
										.createParallelGroup(
												org.jdesktop.layout.GroupLayout.BASELINE)
										.add(jRadioButton3).add(jRadioButton4))
								.addContainerGap(
										org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		jButton1.setText("Get Available Cinemas");
		jButton1.setName("jButton1"); // NOI18N
		jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jButton1MouseClicked(evt);
			}
		});

		jButton2.setText("Generate and Save");
		jButton2.setName("jButton2"); // NOI18N
		jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jButton2MouseClicked(evt);
			}
		});

		fileError.setFont(new java.awt.Font("Lucida Grande", 1, 13));
		fileError.setForeground(new java.awt.Color(255, 0, 0));
		fileError.setText("Invalid filepath");
		fileError.setName("fileError"); // NOI18N

		org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(layout
						.createSequentialGroup()
						.add(20, 20, 20)
						.add(layout
								.createParallelGroup(
										org.jdesktop.layout.GroupLayout.TRAILING)
								.add(fileError)
								.add(layout
										.createSequentialGroup()
										.add(layout
												.createParallelGroup(
														org.jdesktop.layout.GroupLayout.LEADING)
												.add(jLabel3).add(jLabel1)
												.add(jLabel2))
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED)
										.add(layout
												.createParallelGroup(
														org.jdesktop.layout.GroupLayout.LEADING,
														false)
												.add(jTextField2,
														org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
														385, Short.MAX_VALUE)
												.add(jScrollPane1)
												.add(jTextField1,
														org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
														385,
														org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
						.add(layout
								.createParallelGroup(
										org.jdesktop.layout.GroupLayout.LEADING)
								.add(layout
										.createSequentialGroup()
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED)
										.add(jButton2))
								.add(layout
										.createSequentialGroup()
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED)
										.add(jButton1))
								.add(layout
										.createSequentialGroup()
										.add(18, 18, 18)
										.add(layout
												.createParallelGroup(
														org.jdesktop.layout.GroupLayout.TRAILING,
														false)
												.add(org.jdesktop.layout.GroupLayout.LEADING,
														jPanel2,
														org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
														org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE)
												.add(org.jdesktop.layout.GroupLayout.LEADING,
														jPanel1,
														org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
														196,
														org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
						.add(20, 20, 20)));
		layout.setVerticalGroup(layout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(layout
						.createSequentialGroup()
						.add(20, 20, 20)
						.add(layout
								.createParallelGroup(
										org.jdesktop.layout.GroupLayout.BASELINE)
								.add(jLabel1)
								.add(jTextField2,
										org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
										org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
										org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
								.add(jButton1))
						.addPreferredGap(
								org.jdesktop.layout.LayoutStyle.RELATED)
						.add(layout
								.createParallelGroup(
										org.jdesktop.layout.GroupLayout.LEADING)
								.add(layout
										.createSequentialGroup()
										.add(layout
												.createParallelGroup(
														org.jdesktop.layout.GroupLayout.LEADING)
												.add(jLabel2)
												.add(jScrollPane1,
														org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
														194,
														org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED,
												33, Short.MAX_VALUE)
										.add(fileError))
								.add(layout
										.createSequentialGroup()
										.add(jPanel1,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED)
										.add(jPanel2,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
						.addPreferredGap(
								org.jdesktop.layout.LayoutStyle.RELATED)
						.add(layout
								.createParallelGroup(
										org.jdesktop.layout.GroupLayout.BASELINE)
								.add(jLabel3)
								.add(jTextField1,
										org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
										org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
										org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
								.add(jButton2)).addContainerGap()));

		pack();
	}// </editor-fold>

	private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
		try {
			scrapper = new CineSiteScrapper(jTextField2.getText());
			hashCines = scrapper.getCinemasList();
			
			ArrayList<String> cinesList = new ArrayList<String>();
			for (String elem : hashCines.keySet()) {
				cinesList.add(elem);
			}
			Collections.sort(cinesList);
			jList1.setListData(cinesList.toArray());
			
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {

		if (jList1.getSelectedValue() == null) {
			JOptionPane.showMessageDialog(null, "No cinema selected.");

			return;
		}

		if (jTextField1.getText().isEmpty()) {
			JOptionPane.showMessageDialog(null, "No filename specified.");
			return;
		}
		// Get Cinema from the page
		String cinema = (String) jList1.getSelectedValue();
		Cinema cine;
		try {
			cine = scrapper.getCinemaInfoFromPage(jTextField2.getText()
					+ hashCines.get(jList1.getSelectedValue()));
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null,
					"An error occurred: " + e.getMessage());
			e.printStackTrace();
			return;
		}

		// Now write it to the XML file
		XMLBuilder builder = new XMLBuilder();

		try {

			// write the file
			String filename = builder.createXML(cine, jTextField1.getText(),
					(jRadioButton4.isSelected()) ? true : false);

			Desktop d = Desktop.getDesktop();

			d.open(new File(filename));

		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(cine);

	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed"
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
					.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(GUI.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(GUI.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(GUI.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(GUI.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				new GUI().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify
	private javax.swing.ButtonGroup buttonGroup1;
	private javax.swing.ButtonGroup buttonGroup2;
	private javax.swing.JLabel fileError;
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton2;
	private javax.swing.JDialog jDialog1;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JList jList1;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JRadioButton jRadioButton1;
	private javax.swing.JRadioButton jRadioButton2;
	private javax.swing.JRadioButton jRadioButton3;
	private javax.swing.JRadioButton jRadioButton4;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JTextField jTextField1;
	private javax.swing.JTextField jTextField2;
	// End of variables declaration
}
